<template>
  <div>
    <el-upload
      :class="{disUploadStyle: noneBtnImg, disableDelete: !canDelete}"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleBeforeRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-change="handleChange"
      :headers="headers"
      :file-list="formatFileList"
      :action="imagesUploadApi"
      list-type="picture-card"
      :disabled="disabled"
      :limit="limit"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog class="preview_dialog" :append-to-body="true" :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" width="100%" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getToken } from '@/utils/auth';
import { del } from '@/api/picture'

export default {
  props: {
    fileList: {
      type: [String, Array],
      default: ''
    },
    // 上传类型：picture图片 avatar头像 qiNiu 七牛
    type: {
      type: String,
      default: 'picture'
    },
    // 最多上传几张，超过后隐藏上传按钮
    limit: {
      type: Number,
      default: 9
    },
    canDelete: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      pictures: [],
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      noneBtnImg: false
    };
  },
  computed: {
    ...mapGetters(['imagesUploadApi', 'updateAvatarApi', 'qiNiuUploadApi']),
    action() {
      switch (this.type) {
        case 'picture':
          return this.imagesUploadApi;
        case 'avatar':
          return this.updateAvatarApi;
        case 'qiNiu':
          return this.qiNiuUploadApi;
        default:
          return this.imagesUploadApi;
      }
    },
    formatFileList() {
      if (!this.fileList) return []
      if (Array.isArray(this.fileList)) {
        this.noneBtnImg = this.fileList.length >= this.limit
        return this.fileList
      }
      if (typeof this.fileList === 'string') {
        this.noneBtnImg = this.fileList.split(',').length >= this.limit
        return this.fileList.split(',').map(item => ({
          name: item,
          url: `${this.action}/${item}`
        }))
      }
      return []
    }
  },
  methods: {
    getPics() {
      return this.pictures.map(item => item.id).join()
    },
    handleChange(file, fileList) {
      this.noneBtnImg = fileList.length >= this.limit;
    },
    handleSuccess(response, file, fileList) {
      const uid = file.uid
      const id = response.data[0]
      this.pictures.push({ uid, id })
      console.log(this.pictures)
    },
    handleBeforeRemove(file, fileList) {
      for (let i = 0; i < this.pictures.length; i++) {
        if (this.pictures[i].uid === file.uid || file.id === this.pictures[i].id) {
          del(this.pictures[i].id).then(res => {
            this.pictures.splice(i, 1)
            this.noneBtnImg = this.pictures.length >= this.limit
          })
          return true
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.preview_dialog {
  ::v-deep .el-dialog__header {
    height: 50px;
    padding: 0;
  }
}
.disUploadStyle ::v-deep .el-upload--picture-card{
  display: none;
}
.disableDelete ::v-deep .el-upload-list__item-delete {
  display: none!important;
}
</style>
